package com.shiningstars.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.Looper;
import android.support.v4.app.NotificationCompat;

import com.shiningstars.R;
import com.shiningstars.activity.SplashPageActivity;
import com.shiningstars.general.Constants;
import com.shiningstars.general.Messages;
import com.shiningstars.general.Utilities;
import com.shiningstars.php.WebHelper;
import com.shiningstars.tools.ExceptionHandler;

public class StatusService extends Service implements Constants, Messages {

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		try {
			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

			Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

			long pattern[] = { 0, 100, 200, 300, 400 };

			Intent i = new Intent(this, SplashPageActivity.class);
			PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
			final NotificationCompat.Builder builder1 = new NotificationCompat.Builder(this).setContentTitle(SSP)
					.setSmallIcon(R.drawable.ic_launcher).setContentIntent(pi).setAutoCancel(true)
					.setSound(notificationSound).setVibrate(pattern);
			final NotificationCompat.Builder builder2 = new NotificationCompat.Builder(this).setContentTitle(SSP)
					.setSmallIcon(R.drawable.ic_launcher).setContentIntent(pi).setAutoCancel(true)
					.setSound(notificationSound).setVibrate(pattern);

			new Thread() {
				@Override
				public void run() {

					Looper.prepare();

					String oldStatus = Utilities.getSharedPreference(getApplicationContext(), STATUS);
					String oldRole = Utilities.getSharedPreference(getApplicationContext(), ROLE);

					String role = BLANK;

					String mobileNumber = Utilities.getSharedPreference(getApplicationContext(), MOBILE_NUMBER);
					String imeiNumber = Utilities.getSharedPreference(getApplicationContext(), IMEI_NUMBER);

					if (!Utilities.isBlankString(mobileNumber)) {
						WebHelper webHelper = new WebHelper();
						Map<String, String> dataMap = new HashMap<String, String>();

						dataMap.put(MOBILE_NUMBER, mobileNumber);
						dataMap.put(IMEI_NUMBER, imeiNumber);

						try {
							JSONObject statusJSON = webHelper.getUserStatus(dataMap, getApplicationContext());
							if (null != statusJSON && statusJSON.getBoolean(SUCCESS)) {
								String status = statusJSON.getString(STATUS);
								String center = statusJSON.getString(CENTER);
								role = statusJSON.getString(ROLE);

								Utilities.setSharedPreference(getApplicationContext(), CENTER, center);

								if (PENDING.equals(oldStatus) && ACTIVE.equals(status)) {
									builder1.setContentText(REG_STATUS_SUCCESS);
								} else if (PENDING.equals(oldStatus) && INACTIVE.equals(status)) {
									builder1.setContentText(REG_STATUS_INACTIVE);
								} else if (ACTIVE.equals(oldStatus) && INACTIVE.equals(status)) {
									builder1.setContentText(REG_STATUS_INACTIVE);
								} else if (INACTIVE.equals(oldStatus) && ACTIVE.equals(status)) {
									builder1.setContentText(REG_STATUS_ACTIVE);
								}

								if (!oldStatus.equals(status)) {
									dataMap.put(STATUS, status);
									JSONObject appStatusJSON = webHelper.updateAppStatus(dataMap,
											getApplicationContext());

									if (null != appStatusJSON && appStatusJSON.getBoolean(SUCCESS)) {
										Utilities.setSharedPreference(getApplicationContext(), STATUS, status);

										NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
										notificationManager.notify(0, builder1.build());
									}
								}

								if (T.equals(role)) {
									role = TEACHER;
								} else if (A.equals(role)) {
									role = ADMIN;
								}

								if (!role.equals(oldRole)) {
									if (TEACHER.equals(role)) {
										builder2.setContentText(REVOKE_ADMIN);
										Utilities.setSharedPreference(getApplicationContext(), ROLE, TEACHER);
									} else if (ADMIN.equals(role)) {
										builder2.setContentText(GRANT_ADMIN);
										Utilities.setSharedPreference(getApplicationContext(), ROLE, ADMIN);
									}

									NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
									notificationManager.notify(1, builder2.build());
								}
							}
						} catch (JSONException e) {
							Utilities.logError(getApplicationContext(), StatusService.class.getName(), e);
						} catch (IllegalStateException e) {
							Utilities.logError(getApplicationContext(), StatusService.class.getName(), e);
						} catch (IOException e) {
						}

						try {
							if (role.equals(ADMIN)) {
								JSONObject adminCentersJSON = webHelper.getAdminCenters(mobileNumber,
										getApplicationContext());
								if (null != adminCentersJSON && adminCentersJSON.getBoolean(SUCCESS)) {
									int i = 0;
									Set<String> newCenterIdSet = new HashSet<String>();

									while (true) {
										String name = CENTER + (i + 1);
										if (adminCentersJSON.has(name)) {
											i++;
											JSONObject centerJSON = adminCentersJSON.getJSONObject(name);
											String centerId = centerJSON.getString(CENTER_ID);
											String centerName = centerJSON.getString(CENTER_NAME);
											newCenterIdSet.add(C + centerId);
											Utilities.setSharedPreference(getApplicationContext(), C + centerId,
													centerName);
										} else {
											break;
										}
									}

									Set<String> oldCenterIdSet = Utilities.getSharedPreferenceSet(
											getApplicationContext(), ADMIN_CENTERS);

									if (null != oldCenterIdSet) {
										oldCenterIdSet.removeAll(newCenterIdSet);

										for (String centerId : oldCenterIdSet) {
											Utilities.removeSharedPreference(getApplicationContext(), centerId);
										}
									}

									if (i > 0) {
										Utilities.setSharedPreference(getApplicationContext(), ADMIN_CENTERS,
												newCenterIdSet);
									} else {
										Utilities.removeSharedPreference(getApplicationContext(), ADMIN_CENTERS);
									}
								}
							}
						} catch (JSONException e) {
							Utilities.logError(getApplicationContext(), StatusService.class.getName(), e);
						} catch (IllegalStateException e) {
							Utilities.logError(getApplicationContext(), StatusService.class.getName(), e);
						} catch (IOException e) {
						}
					}

					stopService(new Intent(getApplicationContext(), StatusService.class));

					Looper.loop();
					Looper.myLooper().quit();
				}
			}.start();
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), StatusService.class.getName(), e);
		}

		return START_NOT_STICKY;
	}
}